package com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.DeviceRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.StringUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.login.bean.BindUserBean;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BindInfo;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UserBean;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.ss.android.common.lib.AppLogNewUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.StringUtils.getString;

/**
 * Created by wcy on 2017\6\29 0029.
 */

public class BindHelper {
    /**
     * 第三方账户和后台进行绑定
     * @param params
     */
    public static void bind(final BindRequestParams params) {
        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(ThirdService.class).bindUser(JsonUtils.jsonStrToMap(params.toJsonStr())).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new BaseObserver<BindUserBean>() {
            @Override
            public void onResponse(BaseResult<BindUserBean> bindUserBeanBaseResult, BindUserBean bindUserBean, Disposable disposable) {
                if (bindUserBean == null) {
                    return;
                }
                ToastUtil.showMessage(Xutils.getContext(),"绑定成功！");
                // 保存用户id
                UserUtils.saveUserId(bindUserBean.user_id);
                // 发送通知告诉绑定成功 回调出去
                BindEvent ev = new BindEvent();
                ev.code = BindEvent.SUCCESS;
                ev.loginType = params.type;
                //ev.bindUserBean = bindUserBean;
                EventBus.getDefault().post(ev);
                // 保存三方登录类型
                StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME, Constants.LOGIN_TYPE, params.type);
            }
            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
                ToastUtil.showMessage(Xutils.getContext(),"登录失败！");
                BindEvent ev = new BindEvent();
                ev.code = BindEvent.FAILED;
                ev.loginType = params.type;
                // 登录失败 回调信息出去
                EventBus.getDefault().post(ev);
            }
        });
    }

    /**
     * 设备id去注册产生userid
     */
    public static void regiserByDeviceId() {
        if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
            return;
        }
        if(!TextUtils.isEmpty(MMKVDefaultManager.getInstance().getDeviceUserId()) && UserUtils.isLogin()){
            return;
        }
        // 沒有获取权限不让注册
        if (ActivityCompat.checkSelfPermission(Xutils.getContext(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        DeviceRequestParams params = new DeviceRequestParams();
        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(PersonCenterService.class).registerByDeviceId(JsonUtils.jsonStrToMap(params.toJsonStr())).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new BaseObserver<UserBean>() {

            @Override
            @SuppressLint("ApplySharedPref")
            public void onResponse(BaseResult<UserBean> bindUserBeanBaseResult, UserBean bindUserBean, Disposable disposable) {
                if (bindUserBean == null) {
                    return;
                }
                // 保存用户id
                UserUtils.saveUserId(bindUserBean.user_id);
                MMKVDefaultManager.getInstance().setDeviceUserId(bindUserBean.user_id);
                // 保存用户id对应的阅读信息
                //DiskLruCacheUtils.put(bindUserBean.user_id, bindUserBean);
                //获取广告的后台配置
                ADConfigs.updateAdConfig();

                //头条上报游客模式事件
                AdPresenter.touTiaoEvent(R.string.tourists_mode_event,getString(R.string.TOU_TIAO_USER_ID),UserUtils.getUserId());
            }
            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
            }
        });
    }


    public static void bindAlipayWitdraw(Map<String,String> params){
        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(ThirdService.class).bindAlipayWithdraw(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onResponse(BaseResult<String> stringBaseResult, String s, Disposable disposable) {
                        BindInfo event = new BindInfo(true);
                        event.nickname = params.get("nickname");
                        event.type = BindInfo.TYPE_ALIPAY;
                        EventBus.getDefault().post(event);
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        EventBus.getDefault().post(new BindInfo(false));
                    }
                });

    }

    public static void bindWxWitdraw(Map<String,String> params){

        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(ThirdService.class).bindWxWithdraw(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onResponse(BaseResult<String> stringBaseResult, String s, Disposable disposable) {
                        BindInfo event = new BindInfo(true);
                        event.nickname = params.get("nickname");
                        event.type = BindInfo.TYPE_WECHAT;
                        EventBus.getDefault().post(event);
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        EventBus.getDefault().post(new BindInfo(false));
                    }
                });
    }
}
